﻿/**************************************************************************
创建时间:	2020/5/13
作	  者:	张存
邮 	  箱:	zhangcunliang@126.com

描	述：
记	录：
***************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using ZhCun.DbCore.BuildSQLText;
using ZhCun.Utils;
using ZhCun.Utils.Helpers;
using ZhCun.Win.Controls;
using ZhCun.Win.Extend;
using ZhCun.Win.ExtendGridCombox;
using ZhCun.Win.ExtendGridView;
using ZhCun.Win.ExtendSearch;

namespace ZhCun.Win
{
    public partial class FrmBase : DockContent, IFormContainer
    {
        public FrmBase()
        {
            InitializeComponent();
        }

        #region 属性

        /// <summary>
        /// 当前用户Id
        /// </summary>
        [Browsable(false)]
        protected internal static string CurrentUserId { set; get; }
        /// <summary>
        /// 是否管理员
        /// </summary>
        [Browsable(false)]
        protected internal static bool IsManager { set; get; }

        string _ContainerName;
        /// <summary>
        /// 窗体对象标识，默认为类型全称
        /// </summary>
        [Browsable(false)]
        public virtual string ContainerName
        {
            get
            {
                if (_ContainerName.IsEmpty())
                {
                    _ContainerName = this.GetType().ToString();
                }
                return _ContainerName;
            }
            protected set
            {
                _ContainerName = value;
            }
        }

        /// <summary>
        /// 自动初始化GridView
        /// </summary>
        [Description("自动初始化GridView")]
        public bool AutoInitGridView { set; get; } = true;
        /// <summary>
        /// 控件权限参数
        /// </summary>
        [Browsable(false)]
        public string ControlRightsArgs { set; get; }

        #endregion

        private void FrmBase_Load(object sender, EventArgs e)
        {
            //“HideOnClose”属性很重要，该属性一般设置为True，
            //就是指你关闭窗口时，窗体只是隐藏而不是真的关闭。
            this.HideOnClose = false;

            InitStyle();

            if (!DesignMode)
            {
                if (!Config.Settings.FormIcon.IsEmpty())
                {
                    this.Icon = new Icon(Config.Settings.FormIcon);
                }

                InitLabelMsg();
                InitTabHeadMenu();
                InitKeyDown();
                InitAutoGridView();
                this.InitControlRights();
            }
        }

        #region 初始化样式

        void InitStyle()
        {
            this.Font = new System.Drawing.Font("微软雅黑", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
        }

        #endregion

        #region 消息框

        /// <summary>
        /// 打开正常对话框(将来改造多语言准备)
        /// </summary>
        protected void ShowMessageBox(string msg)
        {
            MessageBox.Show(msg);
        }
        /// <summary>
        /// 消息提示
        /// </summary>
        protected LabelMessage MsgTips { set; get; }
        /// <summary>
        /// 初始化提示框
        /// </summary>
        void InitLabelMsg()
        {
            MsgTips = new LabelMessage();
            MsgTips.SetControlHost(this);
        }
        /// <summary>
        /// 显示消息
        /// </summary>
        public void ShowMessage(string msg)
        {
            MsgTips.ShowTips(msg);
        }
        /// <summary>
        /// 询问提示框,点击OK 返回true
        /// </summary>
        public bool ShowQuestion(string msg, string caption, params object[] msgArgs)
        {
            string msgText = string.Format(msg, msgArgs);
            DialogResult r = MessageBox.Show(msgText, caption, MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button2);
            return r == DialogResult.OK ? true : false;
        }
        /// <summary>
        /// 输入对话框
        /// </summary>
        public bool ShowInput(Func<string, ApiResult> SaveHandle, string title, string defaultStr = null)
        {
            FrmInput frm = new FrmInput(SaveHandle, defaultStr);
            if (!title.IsEmpty())
            {
                frm.Text = title;
            }
            return frm.ShowDialog() == DialogResult.OK;
        }
        /// <summary>
        /// 打开选择treeview对话框
        /// </summary>
        /// <param name="InitTreeHandle">初始化treeview的方法</param>
        /// <param name="OnSelected">选中后触发校验</param>
        public bool ShowTreeSelect(Action<TreeView> InitTreeHandle, Func<TreeView, ApiResult> OnSelected, string title = null)
        {
            FrmSelectTree frm = new FrmSelectTree();
            frm.InitTreeHandle = InitTreeHandle;
            frm.OnSelected = OnSelected;
            if (!title.IsEmpty())
            {
                frm.Text = title;
            }
            return frm.ShowDialog() == DialogResult.OK;
        }

        #endregion

        #region 透明层遮罩等待

        OpaqueLayer _OpaqueLayer;

        /// <summary>
        /// 遮罩层控件
        /// </summary>
        public OpaqueLayer OpaqueLayer
        {
            get
            {
                if (_OpaqueLayer == null)
                {
                    _OpaqueLayer = new OpaqueLayer();
                }
                return _OpaqueLayer;
            }
        }



        /// <summary>
        /// 使用遮罩开始长时间工作
        /// </summary>
        public void StartWorking(Action WorkHandle, Action WorkAfterHandle = null)
        {
            OpaqueLayer.ShowOpaqueLayer(this);
            Task.Factory.StartNew(() =>
            {
                WorkHandle();
                OpaqueLayer.HideOpaqueLayer();
                WorkAfterHandle?.Invoke();
            });
        }

        #endregion

        #region 关闭,关闭其它,关闭所有窗体

        void InitTabHeadMenu()
        {
            tsmiCloseForm.Click += TsmiCloseForm_Click;

            tsmiColeOtherForm.Click += TsmiCloseOtherForm_Click;

            tsmiCloseAllForm.Click += TsmiCloseAllForm_Click;
        }

        /// <summary>
        /// 关闭当前窗体
        /// </summary>
        protected void TsmiCloseForm_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        /// <summary>
        /// 关闭其它窗体
        /// </summary>
        protected void TsmiCloseOtherForm_Click(object sender, EventArgs e)
        {
            IDockContent[] documents = DockPanel.DocumentsToArray();
            foreach (IDockContent content in documents)
            {
                if (!content.Equals(this))
                {
                    content.DockHandler.Close();
                }
            }
        }
        /// <summary>
        /// 关闭tab标签中的所有窗体
        /// </summary>
        protected void TsmiCloseAllForm_Click(object sender, EventArgs e)
        {
            IDockContent[] documents = DockPanel.DocumentsToArray();
            foreach (IDockContent content in documents)
            {
                content.DockHandler.Close();
            }
        }

        #endregion

        #region 高级搜索

        /// <summary>
        /// 实现高级搜索
        /// </summary>
        /// <param name="sql">SqlBuilder对象</param>
        /// <param name="SearchAfter">搜索框点击确认后的处理方法</param>
        protected void ADSearch(ISqlBuilder sql, Action SearchAfter, DataGridView dgv = null)
        {
            string dgvName = dgv?.Name;
            if (dgvName.IsEmpty()) dgvName = "dgv";
            FrmADSearch frm = new FrmADSearch(sql, dgvName);
            if (frm.ShowSearch(this))
            {
                SearchAfter();
            }
        }

        #endregion

        #region 共通快捷键

        void InitKeyDown()
        {
            if (IsManager)
            {
                KeyDown += Form_KeyDown;
                KeyPreview = true;
            }
        }

        private void Form_KeyDown(object sender, KeyEventArgs e)
        {
            if (!IsManager) return;
            if (Control.ModifierKeys == Keys.Control && e.KeyCode == Keys.Oemtilde)
            {
                //GridViewColumn
                FrmGridColumn frm = new FrmGridColumn();
                frm.MinimizeBox = false;
                frm.Owner = this;
                frm.ShowDialog();
                return;
            }

            if (Control.ModifierKeys == Keys.Control && e.KeyCode == Keys.D1)
            {
                FrmGridCombox frm = new FrmGridCombox();
                frm.MinimizeBox = false;
                frm.Owner = this;
                frm.ShowDialog();
                return;
            }
        }

        #endregion

        #region 自动初始化GridView

        void InitAutoGridView()
        {
            if (AutoInitGridView)
            {
                this.InitGridView();
            }
        }

        #endregion

        #region 表格选择器（ComboxGrid）

        static ComboxGrid _CoGrid;
        /// <summary>
        /// 选择器对象
        /// </summary>
        [Browsable(false)]
        public ComboxGrid CoBoxGrid
        {
            get
            {
                if (_CoGrid == null) _CoGrid = new ComboxGrid();
                return _CoGrid;
            }
        }
        /// <summary>
        /// 初始化表格选择器
        /// </summary>
        public ComboxGridArgs[] InitCoBoxGrid(params ArgInitCoBoxGrid[] args)
        {
            CoBoxGrid.Clear();
            var r = this.InitCoBoxGrid(CoBoxGrid, args);
            return r;
        }

        ///// <summary>
        ///// 初始化单个控件 表格选择器
        ///// </summary>
        //public ComboxGridArgs InitCoBoxGrid(EditText txt, Func<string, object> GetDataHandle)
        //{
        //    var arg =
        //    InitCoBoxGrid(new ArgInitCoBoxGrid 
        //    { 
        //        Txt = txt,
        //        GetDataSource = GetDataHandle
        //    });
        //    if (arg?.Length > 0) 
        //    {
        //        return arg[0];
        //    }
        //    return null;
        //}

        #endregion

        #region 反射创建窗体

        /// <summary>
        /// 创建form的方法，可自定义方式，如：spring
        /// </summary>
        /// <param name="name">name格式为：“类全名,程序集”</param>
        /// <returns>返回FrmBase</returns>
        protected virtual FrmBase CreateForm(string name)
        {
            var frm = ReflectionHelper.CreateInstance<FrmBase>(name);
            return frm;
        }

        #endregion
    }
}